package com.rjwh.dingdong.client.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings;
import android.telephony.TelephonyManager;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

/**
 * Created by wby on 2016/6/1.
 */
public class DeviceUuidFactory {
    protected static final String PREFS_FILE = "device_id.xml";
    protected static final String PREFS_DEVICE_ID = "device_id";


    public static String getUUID(Context context) {
        String deviceid = ((TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        if (deviceid == null || deviceid.isEmpty()) {
            deviceid = createDeviceId(context).toString();
        }
        return deviceid;
    }

    public static UUID createDeviceId(Context context) {
        UUID uuid;
        synchronized (DeviceUuidFactory.class) {

            final SharedPreferences prefs = context
                    .getSharedPreferences(PREFS_FILE, 0);
            final String id = prefs.getString(PREFS_DEVICE_ID, null);
            if (id != null) {
                // Use the ids previously computed and stored in the
                // prefs file
                uuid = UUID.fromString(id);
            } else {
                final String androidId = Settings.Secure
                        .getString(context.getContentResolver(),
                                Settings.Secure.ANDROID_ID);
                try {
                    if (!"9774d56d682e549c".equals(androidId)) {
                        uuid = UUID.nameUUIDFromBytes(androidId
                                .getBytes("utf8"));
                    } else {
                        final String deviceId = ((TelephonyManager) context
                                .getSystemService(Context.TELEPHONY_SERVICE))
                                .getDeviceId();
                        uuid = deviceId != null ? UUID
                                .nameUUIDFromBytes(deviceId
                                        .getBytes("utf8")) : UUID
                                .randomUUID();
                    }
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
                // Write the value out to the prefs file
                prefs.edit()
                        .putString(PREFS_DEVICE_ID, uuid.toString())
                        .commit();
            }
            return uuid;
        }
    }

}
